import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || '/api',
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    console.log('发送API请求:', config.method?.toUpperCase(), config.url)
    console.log('请求数据:', config.data)
    console.log('baseURL:', config.baseURL)
    
    // 添加token
    if (store.getters['user/token']) {
      config.headers['Authorization'] = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    console.log('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    console.log('收到API响应:', response.status, response.config.url)
    console.log('响应数据:', response.data)
    
    const res = response.data
    
    // 如果返回的状态码不是200，说明接口有问题
    if (response.status !== 200) {
      console.error('API响应状态码不是200:', response.status)
      ElMessage({
        message: res.message || '请求失败',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || '请求失败'))
    }
    
    // 检查业务逻辑状态码，如果code不是200或0，说明业务逻辑失败
    if (res.code !== undefined && res.code !== 200 && res.code !== 0) {
      console.error('业务逻辑失败:', res.code, res.message)
      ElMessage({
        message: res.message || '操作失败',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || '操作失败'))
    }
    
    console.log('API响应成功，返回数据:', res)
    return res
  },
  error => {
    console.log('err' + error)
    
    let message = '请求失败'
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          message = '未授权，请重新登录'
          // 清除token并跳转到登录页
          store.dispatch('user/resetState')
          window.location.href = '/login'
          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = data?.message || `连接错误${status}`
      }
    } else if (error.code === 'ECONNABORTED') {
      message = '请求超时'
    } else {
      message = '网络连接异常'
    }
    
    ElMessage({
      message,
      type: 'error',
      duration: 5 * 1000
    })
    
    return Promise.reject(error)
  }
)

export default service
